﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web;

namespace Universal
{
    public class JS
    {
        /// <summary>
        /// 关闭当前窗口
        /// </summary>
        public static void CloseWindow()
        {
            string js = @"<Script language='JavaScript'>
                    window.close();  
                  </Script>";
            HttpContext.Current.Response.Write(js);
            HttpContext.Current.Response.End();
        }
        /// <summary>
        /// 刷新父窗口，用于页面处理数据后
        /// </summary>
        public static void RefreshParentData()
        {
            string js = @"<Script language='JavaScript'>
                   window.opener.location.href=window.opener.location.href;
                  </Script>";
            HttpContext.Current.Response.Write(js);
        }
        /// <summary>
        /// 运行js片段
        /// </summary>
        /// <param name="message">js代码</param>
        public static void RunJS(string message)
        {
            message = DeleteUnVisibleChar(message);
            string js = @"<Script language='JavaScript'>
                    " + message + "</Script>";
            Page currentPage = System.Web.HttpContext.Current.Handler as Page;
            if (currentPage != null)
            {
                currentPage.ClientScript.RegisterStartupScript(typeof(Page), "runJS", js);
            }
        }
        /// <summary>
        /// 弹出JavaScript小窗口
        /// </summary>
        /// <param name="js">窗口信息</param>
        public static void Alert(string message)
        {
            message = DeleteUnVisibleChar(message);
            string js = @"<Script language='JavaScript'>
                    alert('" + message + "');</Script>";
            Page currentPage = System.Web.HttpContext.Current.Handler as Page;
            if (currentPage != null)
            {
                currentPage.ClientScript.RegisterStartupScript(typeof(Page), "alert", js);
            }
        }

        /// <summary>
        /// 删除不可见字符
        /// </summary>
        /// <param name="sourceString"></param>
        /// <returns></returns>
        public static string DeleteUnVisibleChar(string sourceString)
        {
            System.Text.StringBuilder sBuilder = new System.Text.StringBuilder(131);
            for (int i = 0; i < sourceString.Length; i++)
            {
                int Unicode = sourceString[i];
                if (Unicode >= 16)
                {
                    sBuilder.Append(sourceString[i].ToString());
                }
            }
            return sBuilder.ToString();
        }

    }

}
